package com.example.uchain.controller;

import cn.hutool.json.JSONObject;
import com.example.uchain.demo.PageBean;
import com.example.uchain.demo.Result;
import com.example.uchain.demo.Trade;
import com.example.uchain.demo.dto.TradeCountDTO;
import com.example.uchain.service.TradeService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.time.format.DateTimeFormatter;
import java.util.List;

@RestController
@Slf4j//日志用的注解
@Api(tags = "交易信息")
public class TradeController {

    @Autowired
    private TradeService tradeService;

    @GetMapping("/queryTrading")
    @ApiOperation("分页查询交易信息")
    public Result page(@RequestParam(defaultValue = "1") Integer Page,
                       @RequestParam(defaultValue = "10") Integer pageSize,
                       String ownerName,
                       String workName ,
                       Integer CRId,
                       String workType,
                       String authorization,
                       String blockAddress,
                       Integer code){

        log.info("分页查询交易信息 参数:{},{},{},{},{},{},{},{},{}",Page,pageSize,ownerName,workName,CRId,workType,authorization,blockAddress,code);
        PageBean pageBean=tradeService.page(Page,pageSize,ownerName,workName,CRId,workType,authorization,blockAddress,code);
        System.out.println(pageBean);
        return Result.success(pageBean);
    }

    @GetMapping("/queryTrading1")
    @ApiOperation("分页查询出售版权信息")
    public Result page1(@RequestParam(defaultValue = "1") Integer Page,
                       @RequestParam(defaultValue = "10") Integer pageSize,
                       String ownerName,
                       String workName ,
                       Integer CRId,
                       String workType,
                       String authorization,
                       String blockAddress,
                       Integer code){

        log.info("分页查询出售版权信息 参数:{},{},{},{},{},{},{},{},{}",Page,pageSize,ownerName,workName,CRId,workType,authorization,blockAddress,code);
        PageBean pageBean=tradeService.page1(Page,pageSize,ownerName,workName,CRId,workType,authorization,blockAddress,code);
        return Result.success(pageBean);
    }
    @GetMapping("/queryTrading2")
    @ApiOperation("分页查询出售版权信息")
    public Result page2(@RequestParam(defaultValue = "1") Integer Page,
                        @RequestParam(defaultValue = "10") Integer pageSize,
                        String ownerName,
                        String workName ,
                        Integer CRId,
                        String workType,
                        String authorization,
                        String blockAddress,
                        Integer code,
                        Integer uid){

        log.info("分页查询出售版权信息 参数:{},{},{},{},{},{},{},{},{}",Page,pageSize,ownerName,workName,CRId,workType,authorization,blockAddress,code,uid);
        PageBean pageBean=tradeService.page2(Page,pageSize,ownerName,workName,CRId,workType,authorization,blockAddress,code,uid);
        return Result.success(pageBean);
    }
    @GetMapping("/queryTrading3")
    @ApiOperation("分页查询购买版权信息")
    public Result page3(@RequestParam(defaultValue = "1") Integer Page,
                        @RequestParam(defaultValue = "10") Integer pageSize,
                        String ownerName,
                        String workName ,
                        Integer CRId,
                        String workType,
                        String authorization,
                        String blockAddress,
                        Integer code,
                        Integer uid){

        log.info("分页查询购买版权信息 参数:{},{},{},{},{},{},{},{},{}",Page,pageSize,ownerName,workName,CRId,workType,authorization,blockAddress,code,uid);
        PageBean pageBean=tradeService.page3(Page,pageSize,ownerName,workName,CRId,workType,authorization,blockAddress,code,uid);
        return Result.success(pageBean);
    }

    @GetMapping("/queryTrading4")
    @ApiOperation("分页查询购买版权信息")
    public Result page4(@RequestParam(defaultValue = "1") Integer Page,
                        @RequestParam(defaultValue = "10") Integer pageSize,
                        String ownerName,
                        String workName ,
                        Integer CRId,
                        String workType,
                        String authorization,
                        String blockAddress,
                        Integer code,
                        Integer uid){

        log.info("分页查询购买版权信息 参数:{},{},{},{},{},{},{},{},{}",Page,pageSize,ownerName,workName,CRId,workType,authorization,blockAddress,uid);
        PageBean pageBean=tradeService.page4(Page,pageSize,ownerName,workName,CRId,workType,authorization,blockAddress,code,uid);
        return Result.success(pageBean);
    }

    @PostMapping("/trade")
    @ApiOperation("新增购买版权信息")
    public Result AddTrade(@RequestBody Trade trade){

        log.info("新增购买版权信息: {}",trade);
        tradeService.AddTrade(trade);
        return Result.success();
    }

    @DeleteMapping("/trade")
    @ApiOperation("根据id删除订单信息")
    public Result deleteTradeById(@RequestParam("TId") Integer TId){
        log.info("根据id删除订单信息: {}",TId);
        return tradeService.deleteTradeById(TId);
    }


    @GetMapping("tradeFindByUid")
    @ApiOperation("根据id查询该条交易信息")
    public Result tradeFindByUid(Integer uid){
        log.info("根据id查询该条交易信息: {}",uid);
        tradeService.tradeFindByUid(uid);
        return Result.success();
    }

    @PutMapping( "/trade")
    @ApiOperation("修改挂牌版权信息")
    public Result updateById(@RequestBody Trade trade){
        log.info("修改挂牌版权信息: {}", trade);
        tradeService.updateById(trade);
        return Result.success();
    }
    @PutMapping( "/trade1")
    @ApiOperation("修改购买状态信息")
    public Result updateById1(@RequestBody Trade trade){
        log.info("修改购买状态信息: {}", trade);
        tradeService.updateById1(trade);
        return Result.success(trade);
    }
    @PutMapping( "/trade2")
    @ApiOperation("修改收藏状态信息")
    public Result updateById2(@RequestBody Trade trade){
        log.info("修改收藏状态信息: {}", trade);
        tradeService.updateById2(trade);
        return Result.success(tradeService.findAll1(trade.getCRId()));
    }

    @PutMapping( "/trade3")
    @ApiOperation("修改展示状态信息")
    public Result updateById3(@RequestBody Trade trade){
        log.info("修改展示状态信息: {}", trade);
        tradeService.updateById3(trade);
        return Result.success(tradeService.findAll1(trade.getCRId()));
    }
    @GetMapping("/trade11")
    @ApiOperation("查看热门权益人信息")
    public Result findAllPeople() {
        log.info("查看热门权益人信息");
        List<Trade> treadList = tradeService.findAllPeople();
        return Result.success(treadList);
    }
    //交易信息上链 ——> 交易凭证
    @PostMapping("/addChain1")
    @ApiOperation("交易信息上链")
    public Result AddChain1(@RequestBody JSONObject param){
        Trade t = new Trade();
        t.setCRId((Integer) param.get("CRId"));
        t.setWorkName((String) param.get("workName"));
        t.setWorkType((String) param.get("workType"));
        t.setBlockAddress((String)param.get("blockAddress"));
        t.setAuthorization((String) param.get("authorization"));
        t.setPrice((Integer) param.get("price"));
        log.info("交易信息上链: {}",t);
        return tradeService.AddChain1(t);
    }

    @GetMapping("/tradeCount")
    @ApiOperation("总订单数量和七日内新增订单数量")
    public Result tradeCount(){
        TradeCountDTO counts = tradeService.tradeCount();
        return Result.success(counts);
    }
    @GetMapping("/OrderAndCount")
    @ApiOperation("买卖版权数量TOP10用户")
    public Result OrderAndCount(){
        TradeCountDTO counts = tradeService.OrderAndCount();
        return Result.success(counts);
    }
    @GetMapping("/export")
    @ApiOperation("导出订单数据")
    public void exportOrderData(HttpServletResponse response) throws IOException {
        long startTime = System.currentTimeMillis();
        // 设置响应头
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("UTF-8");
        String encodedFilename = URLEncoder.encode("订单数据.xlsx", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment; filename=\"" + encodedFilename + "\"");

        // 创建Excel工作簿
        try (XSSFWorkbook workbook = new XSSFWorkbook();
             ServletOutputStream out = response.getOutputStream()) {

            XSSFSheet sheet = workbook.createSheet("订单数据");
            Row titleRow = sheet.createRow(0);
            String[] titles = {"交易编号", "作品编号", "卖家昵称", "卖家电话", "作品名称", "作品属性",
                              "作品区块地址", "授权方式", "交易价格", "交易时间", "买家编号"};

            // 填充标题行
            for (int i = 0; i < titles.length; i++) {
                titleRow.createCell(i).setCellValue(titles[i]);
            }

            // 查询数据（建议分页或流式处理）
            List<Trade> orderList = tradeService.getAllTradings();
            log.info("开始导出订单数据，总记录数：{}", orderList.size());

            // 填充数据行
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            int rowNum = 1;
            for (Trade order : orderList) {
                Row dataRow = sheet.createRow(rowNum++);
                dataRow.createCell(0).setCellValue(order.getTId());
                dataRow.createCell(1).setCellValue(order.getCRId());
                dataRow.createCell(2).setCellValue(order.getOwnerName());
                dataRow.createCell(3).setCellValue(order.getOwnerContact());
                dataRow.createCell(4).setCellValue(order.getWorkName());
                dataRow.createCell(5).setCellValue(order.getWorkType());
                dataRow.createCell(6).setCellValue(order.getBlockAddress());
                dataRow.createCell(7).setCellValue(order.getAuthorization());
                dataRow.createCell(8).setCellValue(order.getPrice());
                dataRow.createCell(9).setCellValue(
                    order.getTreadTime() != null ?
                    order.getTreadTime().format(formatter) : ""
                );
                dataRow.createCell(10).setCellValue(order.getUid());
            }

            // 自动调整列宽
            for (int i = 0; i < titles.length; i++) {
                sheet.autoSizeColumn(i);
            }

            // 写入响应流
            workbook.write(out);
            log.info("导出完成，耗时：{}ms", (System.currentTimeMillis() - startTime));
        } catch (Exception e) {
            log.error("导出订单数据失败", e);
            throw new IOException("导出失败，请联系管理员", e);
        }
}
}
